<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.io.File" %>
<%@ page import="sun.misc.BASE64Encoder" %>
<%@ page import="java.io.InputStream" %>
<%@ page language="java" pageEncoding="UTF-8" isErrorPage="true" %>
<%
	request.setCharacterEncoding("UTF-8");
	response.setCharacterEncoding("UTF-8");

	if("POST".equals(request.getMethod())) {

		//登录
		Cookie usernameCookie = new Cookie("username", URLEncoder.encode(request.getParameter("username"), "UTF-8"));  //中文(unicode)必须编码，否则下面 addCookie 那会报错。
		Cookie visittimesCookie = new Cookie("visitTimes", "0");
		response.addCookie(usernameCookie);
		response.addCookie(visittimesCookie);

		//Base64编码。cookie中不仅可以存ascii字符和unicode字符，还可以存储二进制数据，不过先要转base64。（cookie中数据不要过多，会影响速度）
		File file = new File(request.getServletContext().getRealPath("/images/statistics.png"));
		byte[] binary = new byte[(int) file.length()];
		InputStream ins = request.getServletContext().getResourceAsStream("/images/" + file.getName());  //getResourceAsStream方法中的参数必须是相对路径，用绝对路径发现报错，通过这个方法直接拿到输入流了。
		ins.read(binary);
		String content = BASE64Encoder.class.newInstance().encode(binary);
		Cookie cookie = new Cookie("file", URLEncoder.encode(content, "UTF-8"));  //必须编码
		response.addCookie(cookie);

		response.sendRedirect(request.getContextPath() + "/session/cookie.jsp");  //重定向
		return;
	}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>请先登录</title>
</head>
<body>
<div align="center" style="margin:10px; ">
	<fieldset>
		<legend>登录</legend>
		<form action="/session/login.jsp" method="post">
			<table>
				<tr>
					<td>
					</td>
					<td>
						<span><img src="/images/errorstate.gif"></span>
						<span style="color:red; "><%=exception.getMessage() %></span>
					</td>
				</tr>
				<tr>
					<td>
						帐号：
					</td>
					<td>
						<input type="text" name="username" style="width:200px; ">
					</td>
				</tr>
				<tr>
					<td>
						密码：
					</td>
					<td>
						<input type="password" name="password" style="width:200px; ">
					</td>
				</tr>
				<tr>
					<td>
					</td>
					<td>
						<input type="submit" value=" 登  录 " class="button">
					</td>
				</tr>
			</table>
		</form>
	</fieldset>
</div>
</body>
</html>
